package SM.BusinessLogic;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBService {

		public static void ExecuteQuery(String query, String... params)
		{
			Connection connection = null;
			PreparedStatement statement = null;
			
			try
			{
				connection = DBAccess.MakeConnection();
				
				statement = connection.prepareStatement(query);
				
				int i = 1;
				
				for(String param : params)
				{
					statement.setString(i, param);
					i++;
				}
				
				statement.executeUpdate();
				
			}catch(SQLException SQLEx)
			{
				System.out.println("SQLException in execute insert query\nError : " + SQLEx.getMessage());
			}
			finally
			{
				DBAccess.CloseConnection(connection);
				DBAccess.CloseStatement(statement);
			}
		}
		

		public static ResultSet ExecuteProcedure(Connection connection, CallableStatement statement) //for select all procedures
		{
			if(connection == null)
			{
				System.out.println("Connection null.. Cleaning off");
				return null;
			}
			
		
			try {
					
					ResultSet resultSet = statement.executeQuery();
					
					return resultSet;
			}catch(SQLException SQLEx) {
				System.out.println("SQLException in ExecuteProcedure \nCode : " + SQLEx.getErrorCode() + "\nMessage : " + SQLEx.getMessage() );
			}
			finally {
				
			}
			return null;
		}
		
		public static ResultSet ExecuteStatement(Connection connection, PreparedStatement statement) //for select all procedures
		{
			if(connection == null)
			{
				System.out.println("Connection null.. Cleaning off");
				return null;
			}
			
		
			try {
					
					ResultSet resultSet = statement.executeQuery();
					
					return resultSet;
			}catch(SQLException SQLEx) {
				System.out.println("SQLException in ExecuteProcedure \nCode : " + SQLEx.getErrorCode() + "\nMessage : " + SQLEx.getMessage() );
			}
			finally {
				
			}
			return null;
		}
		
		public static boolean IsRecordPresent(String selectQuery, String... filters)
		{
			Connection connection = null;
			PreparedStatement statement = null;
			
			try {
				connection = DBAccess.MakeConnection();
			
				statement = connection.prepareStatement(selectQuery);
				
				int i = 1;
				
				for(String filter : filters)
				{
					statement.setString(i, filter);
					i++;
				}
				
				ResultSet resultSet = statement.executeQuery();
				
				int rowCount = 0;
				
				if(resultSet.last())
				{
					rowCount = resultSet.getRow();
				}
				
				return (rowCount == 0) ? false : true;
				
			}catch(SQLException SQLEx)
			{
				System.out.println("SQLException in is single query filter\nError : " + SQLEx.getMessage());
			}
			finally {
				
				DBAccess.CloseConnection(connection);
				DBAccess.CloseStatement(statement);
				
			}
			return false;
		}
}
